package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {


    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;
    @Override
    public Result queryBlogById(Long id) {
        // 1.根据id查询
         Blog blog = this.getById(id);
         if(blog == null){
             return Result.fail("博客不存在");
         }
        // 2.查询用户有关信息
        queryBlogUser(blog);
         // 3.查询blog的点赞信息
        isBlogLiked(blog);
        return null;
    }

    private void isBlogLiked(Blog blog) {
        // 1.获取当前用户
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return;
        }
        Long userId = UserHolder.getUser().getId();
        Long id = blog.getId();
        // 2.判断用户是否已经点赞
        String key = "blog:liked:" + id;
        //Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    /**
     * 查询博客的用户信息
     * @param blog
     */
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 分页查询
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 点赞博客
     * @param id // 博客id
     */
    @Override
    public void likeBlog(Long id) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2.判断用户是否已经点赞
        String key = "blog:liked:" + id;
        //Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score == null){
            // 3.如果未点赞，可以点赞
            // 3.1 数据库点赞数 + 1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if(isSuccess){
                // 3.2 保存用户到redis的sortSet集合中
                stringRedisTemplate.opsForZSet().add(key, userId.toString(),System.currentTimeMillis());
            }

        } else {
            // 4.如果已经点赞，则取消点赞
            // 4.1 数据库点赞数 -1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if(isSuccess){
                // 4.2 从redis的set集合中删除用户
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }

        }
    }

    @Override
    public Result queryBlogLikes(Long id) {
        // 查询博客点赞top5的用户
        String key = "blog:liked:" + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        // 解析用户id
        if(top5 == null || top5.isEmpty()){
            return Result.ok();
        }
        List<Long> userIds = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        // 查询用户信息
        List<UserDTO> collect = userService.query().in("id",userIds).last("ORDER BY FIELD(id, " + StrUtil.join(",", userIds) + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 封装返回结果
        return Result.ok(collect);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        // 2.获取并且设置当前用户id
        blog.setUserId(user.getId());
        // 3.保存blog,判断是否成功
        boolean isSuccess = this.save(blog);
        if(isSuccess){
            // 3.1查询笔记作者的所有fans
            List<Follow> fans = followService.query().eq("follow_user_id", user.getId()).list();
            // 3.2 推送id给所有的fans
            for(Follow follow : fans){
                //3.2.1 获取粉丝id
                Long fanId = follow.getUserId();
                //3.2.2 推送消息（sortSet）
                String key = "feed:" + fanId;
                // 用sortSet的score值，使用当前时间戳作为排序值，好处是可以根据时间戳排序，获取最新消息
                stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
            }
        } else {
            return Result.fail("发布笔记失败");
        }
        // 4.返回结果
        return Result.ok();
    }

    @Override
    public Result queryBlogByFollow(Long max, Integer offset) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2.查询收件箱 ZREVRANGEBYSCORE key MAX min MAX min LIMIT
        String key = "feed:" + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        // 3.解析数据 blogId，minTime 时间戳 offset
        // 3.1 非空判断
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        // 3.2 解析数据
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples){
            // 3.2.1 获取Id
            ids.add(Long.valueOf(typedTuple.getValue()));
           long time = typedTuple.getScore().longValue();
           if(time == minTime){
                os++;
           }else{
              minTime = time;
              os = 1;
           }
            // 3.2.2 获取时间戳（分数）
             minTime = typedTuple.getScore().longValue();
            // 3.2.3 根据id查询blog
        }
        // 4.根据id查询blog
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id, " + StrUtil.join(",", ids) + "))").list();
        for(Blog blog : blogs){
            // 4.1 查询用户有关信息
            queryBlogUser(blog);
            // 4.2 查询blog的点赞信息
            isBlogLiked(blog);
        }
        // 5.封装结果
        ScrollResult result = new ScrollResult();
        result.setList(blogs);
        result.setOffset(os);
        result.setMinTime(minTime);
        return Result.ok(result);

    }
}
